package com.example.myapplication.Sign;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;
import com.example.myapplication.db.DBManager;
import com.example.myapplication.db.DataManager;
import com.example.myapplication.db.domain.UserBean;
import com.mob.MobSDK;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class registerPage extends AppCompatActivity {
    //   注册界面返回按键
    private ImageView register_back;
    //    手机号
    private EditText phoneNum;
    //   验证码
    private EditText captcha;
    //   获取验证码
    public TextView getCaptcha;
    //    密码
    private EditText password;
    //    再次输入密码
    private EditText re_password;
    //    用户协议选项
    private CheckBox agreement_btn;
    //注册按键
    private Button register;

    // 验证码获取计时器
    private final CaptchaCountDownTimer timer = new CaptchaCountDownTimer(60000, 1000);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_page);

        MobSDK.submitPolicyGrantResult(true);

        // 获取到xml中相应对象
        phoneNum = findViewById(R.id.register_phoneNumber);
        captcha = findViewById(R.id.register_captcha);
        getCaptcha = findViewById(R.id.register_get_captcha);
        password = findViewById(R.id.register_password);
        re_password = findViewById(R.id.register_re_password);
        agreement_btn = findViewById(R.id.register_agreement_btn);
        register_back = findViewById(R.id.register_back_btn);
        register = findViewById(R.id.login_btn);

        //  用户协议
        UserAgreement userAgreement = new UserAgreement(findViewById(R.id.register_agreement),registerPage.this);
        userAgreement.setAgreement();

        Log.e("userid", DataManager.userId + "");

        // 注册界面返回到登录界面
        register_back.setOnClickListener(view -> registerPage.this.finish());

        // 注册事件
        register.setOnClickListener(v -> {
            if (!agreement_btn.isChecked()){
                Toast.makeText(getApplicationContext(), "请阅读并同意用户协议", Toast.LENGTH_LONG).show();
                return;
            }
            String phone = phoneNum.getText().toString().trim();
            String code = captcha.getText().toString().trim();//获取输入的验证码
            String errMsg = ValidUtils.checkInfo(
                    phone,
                    password.getText().toString(),
                    re_password.getText().toString()
            );
            if (errMsg != null) {
                Toast.makeText(getApplicationContext(), errMsg, Toast.LENGTH_LONG).show();
            }else {
                SMSSDK.submitVerificationCode("86", phone, code);//对比
            }
        });

        // 获取验证码事件
        getCaptcha.setOnClickListener(view -> {
            regist();//调用注册短信发送的回调接口
            String phone = phoneNum.getText().toString().trim();//获取输入的手机号
            if (TextUtils.isEmpty(phone)){
                Toast.makeText(getApplicationContext(), "手机号码不能为空",Toast.LENGTH_LONG).show();
            }else if (DBManager.findUserByPhone(phone)){
                Toast.makeText(getApplicationContext(), "该手机号已被注册",Toast.LENGTH_LONG).show();
            }else {
                if(ValidUtils.checkTel(phone)){
                    SMSSDK.getVerificationCode("86", phone);
                    timer.start();
                }else {
                    Toast.makeText(getApplicationContext(), "手机号码不合法",Toast.LENGTH_LONG).show();
                }
            }
        });

    }

    // 接口回调函数
    private void regist() {
        EventHandler eh = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {   //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        runOnUiThread(() -> {
                            try {
                                UserBean bean = new UserBean(
                                        phoneNum.getText().toString().trim(),
                                        AESCrypt.encrypt(password.getText().toString()),
                                        null
                                );
                                if (DataManager.toBeBind){
                                    bean.setAlipayCode(DataManager.alipayCode);
                                }
                                if (DBManager.insertUser(bean)){
                                    DataManager.toBeBind = false;
                                    Toast.makeText(getApplication(), "注册成功！", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(registerPage.this, loginPage.class);
                                    startActivity(intent);
                                }else {
                                    Toast.makeText(getApplication(), "注册失败", Toast.LENGTH_SHORT).show();
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                            finish();
                        });
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {    //如果获取到验证码
                        runOnUiThread(() -> Toast.makeText(getApplication(), "验证码已发送", Toast.LENGTH_SHORT).show());
                    }
                } else {
                    runOnUiThread(() -> Toast.makeText(getApplication(), "操作失败，重新获取验证码", Toast.LENGTH_SHORT).show());
                    ((Throwable) data).printStackTrace();
                }
            }
        };
        SMSSDK.registerEventHandler(eh); //注册短信回调
    }


    private class CaptchaCountDownTimer extends CountDownTimer {
        public CaptchaCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            getCaptcha.setClickable(false);
            getCaptcha.setText((l / 1000) + "秒");
        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            getCaptcha.setText("重新获取");
            //设置可点击
            getCaptcha.setClickable(true);
        }
    }
}